package zzg.study.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import zzg.study.protocol.Packet;
import zzg.study.protocol.PacketCodec;

import java.util.List;

/**
 * @Classname PacketCodecHandler
 * @Description netty提供特殊的handle实现编解码
 * @Date 2023/12/3 19:15
 * @Author zhuzhenguo
 */
public class PacketCodecHandler extends MessageToMessageCodec<ByteBuf, Packet> {

    public static final PacketCodecHandler INSTANCE = new PacketCodecHandler();

    private PacketCodecHandler() {

    }

    /**
     * 解码
     * @param ctx ctx
     * @param byteBuf byteBuf
     * @param out 在out中添加解码后的结果对象，就可以自动实现结果向下一个handle传递
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) {
        out.add(PacketCodec.INSTANCE.decode(byteBuf));
    }

    /**
     * 编码
     * @param ctx ctx
     * @param packet packet
     * @param out 实现Packet类型对象到二进制数据的转换
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Packet packet, List<Object> out) {
        ByteBuf byteBuf = ctx.channel().alloc().ioBuffer();
        PacketCodec.INSTANCE.encode(byteBuf, packet);
        out.add(byteBuf);
    }
}
